package dahuiji.common.core;

import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;

import dahuiji.common.entity.Line;
/**
 * 抓取累，根据提供的一条航线抓取数据，现在抓取的是json数据，返回json数据
 * @author Administrator
 *
 */
public class UrlCatch {
	private DateCaozuo dateCaozuo;

	public String getURlString(Line line) throws IOException, ParseException {
		dateCaozuo=new DateCaozuo();
		// http://ws.qunar.com/all_lp.jcp?from=北京&to=昆明&goDate=2013-11-03&backDate=2013-11-03&count=90&packto=2013-11-05&packreturn=2013-11-07&packcount=9&output=json&n=0.23275450749409972&callback=SpringHotRoundtrip.parsedata"
		StringBuffer u = new StringBuffer();
		String unc = "UTF-8";
		u.append("http://ws.qunar.com/all_lp.jcp?from=");
		u.append(URLEncoder.encode(line.getFromCity(), unc));
		u.append("&to=");
		u.append(URLEncoder.encode(line.getToCity(), unc));
		u.append("&goDate=");
		u.append(URLEncoder.encode(dateCaozuo.dateToString(line.getfDate())
				.toString(), unc));
		u.append("&backDate=");
		u.append(URLEncoder.encode(dateCaozuo.dateToString(line.getfDate()),
				unc));
		u.append("&count=90&packto=");
		u.append(URLEncoder.encode(
				dateCaozuo.dateToString(dateCaozuo.addTown(line.getfDate(), 2)),
				unc));
		u.append("&packreturn=");
		u.append(URLEncoder.encode(
				dateCaozuo.dateToString(dateCaozuo.addTown(line.getfDate(), 4)),
				unc));
		u.append("&packcount=9&output=json&n=0.23275450749409972&callback=SpringHotRoundtrip.parsedata");
		String ur = u.toString();
		URL url = new URL(ur);
		URLConnection conn = url.openConnection();
		conn.connect();
		// /InputStreamReader is = new InputStreamReader(conn.getInputStream());
		BufferedReader rd = new BufferedReader(new InputStreamReader(
				conn.getInputStream()));
		String tempLine = rd.readLine();
		StringBuffer tempStr = new StringBuffer();
		while (tempLine != null) {
			tempStr.append(tempLine);
			tempLine = rd.readLine();
		}
		return tempStr.toString();

	}

	public String getLine(Line line) throws ParseException {
		String url = "http://ws.qunar.com/all_lp.jcp?";
		String code = "utf-8";
		Map m = new HashMap();
		m.put("from", line.getFromCity());
		m.put("to", line.getToCity());
		m.put("goDate", dateCaozuo.dateToString(line.getfDate()));
		m.put("backDate", dateCaozuo.dateToString(line.getfDate()));
		m.put("count", 90);
		m.put("packto",
				dateCaozuo.dateToString(dateCaozuo.addTown(line.getfDate(), 2)));
		m.put("packreturn",
				dateCaozuo.dateToString(dateCaozuo.addTown(line.getfDate(), 4)));
		m.put("packcount", 9);
		m.put("output", "json");
		m.put("n", 0.23275450749409972);
		m.put("callback", "SpringHotRoundtrip.parsedata");
		String rus = doPost(url, m, code);
		return rus;
	}

	public String doPost(String reqUrl, Map parameters, String recvEncoding) {
		HttpURLConnection conn = null;
		String responseContent = null;
		try {
			StringBuffer params = new StringBuffer();
			for (Iterator iter = parameters.entrySet().iterator(); iter
					.hasNext();) {
				Entry element = (Entry) iter.next();
				params.append(element.getKey().toString());
				params.append("=");
				params.append(URLEncoder.encode(element.getValue().toString()));
				// params.append(URLEncoder.encode(element.getValue().toString(),recvEncoding));
				params.append("&");
			}

			if (params.length() > 0) {
				params = params.deleteCharAt(params.length() - 1);
			}
			URL url = new URL(reqUrl);
			HttpURLConnection url_con = (HttpURLConnection) url
					.openConnection();
			// url_con.setRequestMethod("get");
			url_con.setConnectTimeout(5000);// （单位：毫秒）jdk
			// 1.5换成这个,连接超时
			url_con.setReadTimeout(5000);// （单位：毫秒）jdk 1.5换成这个,读操作超时
			url_con.setDoOutput(true);
			byte[] b = params.toString().getBytes();
			url_con.getOutputStream().write(b, 0, b.length);
			url_con.getOutputStream().flush();
			url_con.getOutputStream().close();
			InputStream in = url_con.getInputStream();
			if (in != null) {
				BufferedReader rd = new BufferedReader(
						new InputStreamReader(in));

				// BufferedReader rd = new BufferedReader(new
				// InputStreamReader(in,recvEncoding));
				String tempLine = rd.readLine();
				StringBuffer tempStr = new StringBuffer();
				String crlf = System.getProperty("line.separator");
				while (tempLine != null) {
					tempStr.append(tempLine);
					tempStr.append(crlf);
					tempLine = rd.readLine();
				}
				responseContent = tempStr.toString();
				rd.close();
				in.close();
				return responseContent;
			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (conn != null) {
				conn.disconnect();
			}
		}
		return null;
	}

	@Resource
	public void setDateCaozuo(DateCaozuo dateCaozuo) {
		this.dateCaozuo = dateCaozuo;
	}

}
